package com.fomky.queried.plugin.mysql;

import com.fomky.queried.common.connect.RowData;
import com.fomky.queried.common.connect.SchemaColumn;
import io.r2dbc.spi.ColumnMetadata;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;

public class ResultMapFunction implements BiFunction<Row, RowMetadata, RowData> {
    @Override
    public RowData apply(Row row, RowMetadata rowMetadata) {
        List<SchemaColumn> columns = new ArrayList<>();
        Map<String, Object> values = new HashMap<>();
        for (ColumnMetadata columnMetadata : rowMetadata.getColumnMetadatas()) {
            Object value = row.get(columnMetadata.getName());
            // value
            values.put(columnMetadata.getName(), value);
            //
            SchemaColumn column = SchemaColumn.builder()
                    .name(columnMetadata.getName())
                    .type(columnMetadata.getType().getName())
                    .build();
            columns.add(column);
        }

        return RowData.builder()
                .columns(columns)
                .data(values)
                .build();
    }


}
